package cn.zzmx.service;




import cn.zzmx.entity.Role;
import cn.zzmx.mapper.IUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 自定义的方式
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IUserMapper iUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户的用户名: {}", username);
        // TODO 根据用户名，查找到对应的密码，与权限

        cn.zzmx.entity.User myUser = iUserMapper.queryUserByName(username);

        // 封装用户信息，并返回。参数分别是：用户名，密码，用户权限
        User user = new User(username, myUser.getPassword(),
               getAuth(myUser.getRoleList()));
        return user;
    }


    //这个成员方法作用就是返回一个List集合，集合中装入的是角色描述。
    //实际项目中应该是从数据库中获取role描述后封装到这个方法体里面。

    public List<GrantedAuthority> getAuth(List<Role> roleList){

        ArrayList<GrantedAuthority> list = new ArrayList<>();
        for (Role role : roleList) {
            list.add(new SimpleGrantedAuthority(role.getTitle()));
            System.out.println(role);
        }

        return list;
    }
}
